/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {Renderer, render} from '../../renderer';
import * as assign from 'object-assign';

import '../../action';
import * as cx from 'classnames';

@Renderer({
  name: 'crud-field-operation',
  desc: '...',
  test: /(?:^|\/)(?:crud\/(.*?\/)|table\/)field\/operation$/
})
export default class Operation extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    item: PropTypes.object.isRequired,
    type: PropTypes.string.isRequired,
    onRequestAction: PropTypes.func,
    buttons: PropTypes.arrayOf(PropTypes.shape({
      type: PropTypes.oneOf(['icon-button', 'button', 'button-group', 'dropdown-button'])
    }))
  };

  static defaultProps = {
    className: 'btn-operation'
  };

  render() {
    const {
      onRequestAction,
      className,
      buttons,
      disabled,
      item,
      data,
      locals,
      stopClickPropagation,
      $rowIndex,
      $path
    } = this.props;

    return (
      <div className={className} onClick={stopClickPropagation ? e => e.stopPropagation() : null}>
        {buttons.map((button, key) => {
          if (button.type === 'button-group' || button.type === 'dropdown-button') {
            return (
              render(`${$path}/${button.type}`, assign({
                btnClassName: button.btnClassName || 'btn-sm btn-default'
              }, button), {
                key,
                item,
                $rowIndex,
                data,
                disabled,
                locals,
                onRequestAction: button._onClick || onRequestAction
              })
            );
          }

          return (
            render(`${$path}/action`, assign({
              className: cx('btn-sm', button.label ? 'btn-default' : '')
            }, button), {
              key,
              item,
              data,
              disabled,
              locals,
              $rowIndex,
              onRequestAction: button._onClick || onRequestAction
            })
          );
        })}
      </div>
    );
  }
}
